﻿var loginInfo;

try {
    loginInfo = app.getStorage("LOGININFO");

    if (!(loginInfo && (loginInfo = Base64.decode(loginInfo)) && (loginInfo = eval("(" + loginInfo + ")")))) {
        exit();
    }

    if (!(loginInfo.UserId && loginInfo.UserName)) {
        exit();
    }
} catch (e) {
    exit();
}



$.extend(app, {
    msg: function (text) {
        layer.msg(text, { icon: 1, anim: 0, offset: "80px" });
    },
    errMsg: function (text) {
        layer.msg(text, { icon: 2, anim: 6, offset: "80px" });
    },
    confirm: function (text, callback) {
        var layerId = layer.confirm(text, { icon: 3, btn: ["确定", "取消"], title: "操作提示", anim: 0/*, offset: "80px"*/ },
            function () {
                callback();
                layer.close(layerId);
            }, function () {
                layer.close(layerId);
            });
    },
    alert: function (text) {
        layer.alert(text, {
            icon: 0,
            title: "操作提示",
            anim: 0
        });
    },
    choose: function (text, config) {
        var cfg = {
            icon: 0,
            btn: [],
            title: "操作提示",
            anim: 0/*,
        offset: "80px"*/
        };

        var index = 1;

        for (var item in config) {
            cfg.btn.push(item);
            cfg["btn" + index] = config[item];
            ++index;
        }

        var oldBtn1 = cfg.btn1;

        cfg.btn1 = function () {
            oldBtn1();
            layer.close(layerId);
        };

        var layerId = layer.confirm(text, cfg);
    },
    tips: function (element, text) {
        function ShowTips() {
            if (element.jquery) {
                element = element[0];
            }

            var rect = element.getBoundingClientRect();

            if (rect.left <= 0 || rect.top <= 0 || rect.right >= $(window).width() || rect.bottom >= $(window).height()) {
                app.errMsg(text);

                return;
            }

            layer.tips(text, element, {
                tips: [2, '#f33'],
                anim: 6,
                tipsMore: true
            });
        }
        setTimeout(ShowTips, 1);
    },
    showPhoto: function (url) {
        var box = $("<div class=\"hide-img-box\"></div>");
        var img = $("<img />");

        var id = String(parseInt(Math.random() * 100000));

        img.attr("src", url);

        box.append(img);
        $(document.body).append(box);

        layer.open({
            type: 1,
            title: false,
            closeBtn: 1,
            // area: ['80%', '80%'],
            skin: 'layui-layer-nobg img-box',
            shadeClose: true,
            content: box
        });

        return box;
    },
    defaultFailure: function (data) {
        if (data[Consts.code] == 0x10) {
            exit();
        }
    },

    userId: loginInfo.UserId,
    userName: loginInfo.UserName,
    token: loginInfo.Token,
    nickname: loginInfo.Nickname || loginInfo.UserName,
    roleAddress: loginInfo.RoleAddress,
    roleId: loginInfo.RoleId,
    roleName: loginInfo.RoleName
});

function getAreas() {
    var cache = window;
    var const_name = "__Areas_Data__";

    return cache[const_name] || internal();

    function internal() {
        app.serverAsync = false;

        var result;

        app.server({ Command: "ReadAllAreas" }, function (ret) {
            result = ret;
        });

        app.serverAsync = true;

        var map = {};

        $(result).each(function () {
            this.Items = [];
            map[this.Id] = this;
        });

        $(result).each(function () {
            this.Parent = map[this.ParentId];

            if (this.Parent) {
                this.Parent.Items.push(this);
            }
        });

        cache[const_name] = map;

        return map;
    }
}

$.extend(Renderers, {
    price: function (price, retailPrice, unit) {
        return $("<div>")
            .append($("<h5>").html("￥" + retailPrice + "/1" + unit).css("text-decoration", "line-through").css("color", "gray"))
            .append($("<h3>").html("￥" + price + "/1" + unit).css("color", "red")
            );
    },
    area: function (areaId) {
        var area = getAreas()[areaId];

        var ret = $("<div class='area'>");

        while (area) {

            ret.prepend($("<span>").text(area.Name));

            area = area.Parent;
        }

        return ret;
    },
    user: function (userId) {
        var ret = $("<a>");

        if (userId) {
            add(ret, userId);
        }

        return ret;

        function add(ele, uId) {
            var cache = window;
            var const_name = "__User_Renderer__";
            var users_name = "__User_Renderer_Users__";

            var users = cache[users_name] || (cache[users_name] = {});

            if (users[uId]) {
                set(ele, users[uId]);

                return;
            }

            var info = cache[const_name];

            if (!info) {

                cache[const_name] = info = {};

                setTimeout(function () {
                    var info = cache[const_name];

                    var ids = [];

                    for (var id in info) {
                        ids.push(id);
                    }

                    app.server({ Command: "ReadUserInfosByIds", Ids: ids }, function (ret) {
                        $(ret).each(function () {
                            var ele = info[this.Id];

                            if (ele) {
                                set(ele, this);
                            }

                            users[this.Id] = this;
                        });
                    });

                    delete cache[const_name];
                }, 100);
            }
            
            info[uId] = ele;

            function set(ele, user) {
                ele.text(user.Nickname);
            }
        }
    },
    multi: function (value) {
        value = String(value);

        var items = value.split(',');

        var div = $("<div style='padding:5px;'>");

        for (var i = 0; i < items.length; i++) {
            if (items[i]) {
                div.append($("<div style='white-space: nowrap;text-overflow: ellipsis;overflow: hidden;'>" + items[i] + "\n" + "</div>"));
            }
        }

        return div;
    },
});

setInterval(function () {
    $("#Main>.hide-img-box").remove();
}, 60000);

function logged() {
    app.server({ Command: "ReadAllAuthorizedMenus" }, function (result) {
        var menusMap = { "0": {} };

        $(result).each(function () {
            try {
                menusMap[this.Id] = this;

                if (menusMap[this.ParentId].Items) {
                    menusMap[this.ParentId].Items.push(this);
                } else {
                    menusMap[this.ParentId].Items = [this];
                }
            } catch (e) {
                console.error(this);
            }
        });

        var systemName = menusMap[app.appId].Name;

        $("#SystemName").text(systemName);
        $("head>title").text(systemName);

        var rootMenus = menusMap[app.appId].Items;

        var menusElement = $("#Main #Top #Menu");
        var pagesElement = $("#Main #Left #Page");

        $(rootMenus).each(function () {
            menusElement.append(app.format("<div id=\"Menu_@Id\" class=\"item\"><a class=\"text\">@Name</a></div>", this));

            menusElement.find("#Menu_" + this.Id).prop("data", this);
        });

        menusElement.find(".item").click(function () {
            if ($(this).hasClass("active")) {
                return false;
            }

            menusElement.find(".active").removeClass("active");

            $(this).addClass("active");

            pagesElement.find(".item").remove();

            $(this.data.Items).each(function () {
                pagesElement.append(app.format("<div id=\"Page_@Id\" class=\"item\"><span class=\"state icon icon-caret-right\"></span> <span class=\"text\">@Name</span></div>", this));

                pagesElement.find("#Page_" + this.Id).prop("data", this);
            });

            if (activePageId()) {
                pagesElement.find("#Page_" + activePageId()).addClass("active");
            }

            pagesElement.find(".item").click(function () {
                pagesElement.find(".active").removeClass("active");

                $(this).addClass("active");

                app.body.find(">*").remove();

                app.body.append("<h1 style=\"text-align:center;color:#333;position:absolute;width:100%;margin:0;top:40%;\">页面正在加载...</h1>");

                if (this.data.Type != 3) {
                    app.confirm("无效的菜单，因为 -- " + this.data.Name + " -- 不是一个页面。");
                    return false;
                }

                app.loadBody(this.data);

                activePageId(this.data.Id);
            });
        });

        var isActivePage = false;

        if (activePageId()) {
            var PageId = activePageId();
            $(result).each(function () {
                if (this.Id == PageId) {
                    menusElement.find("#Menu_" + this.ParentId).click();

                    pagesElement.find("#Page_" + this.Id).click();

                    isActivePage = true;

                    return false;
                }
            });
        }

        if (!isActivePage) {
            app.msg("欢迎您，" + app.nickname + "!");

            menusElement.find(".item:first").click();
            pagesElement.find(".item:first").click();
        }
    });
}

function activePageId(Value) {
    if (Value) {
        // Set
        location.hash = "#" + Value;

        window.__ActivePageId = Value;
    } else {
        // Get

        if (window.__ActivePageId) {
            return window.__ActivePageId;
        }

        if (location.hash && !isNaN(Value = parseInt(String(location.hash).substr(1)))) {
            window.__ActivePageId = Value;

            return Value;
        }

        return null;
    }
}

function exit() {
    $.removeCookie("LOGININFO");

    window.location = "/login/login.html";
}

logged();

var userButton = $("#Main>#Top>#User input[type=button]");

userButton.val("欢迎您：" + app.nickname + " ▼");

userButton.click(function (e) {
    e.stopPropagation();

    app.removeMenus();

    var menu = app.showMenu([
        {
            text: "修改密码",
            click: function (e) {
                var Frame = app.show($("#TempUpdatePasswordFrame"));

                app.apply(Frame, { UserName: app.userName });

                Frame.on("submitted", exit);
            }
        }, ",", {
            text: "退出",
            click: function (e) {
                app.server({ Command: "AdminExit" }, exit);
            }
        }
    ]);

    menu.css("width", "130px");
    menu.css("top", "40px");
    menu.css("right", "5px");
});

$("#TempUpdatePasswordFrame").on("process", function (e, data) {
    if (data.NewPassword != data.NewPassword2) {
        app.errMsg("两次新密码输入不一致！");

        throw "NewPassword";
    }

    data.Password = app.md5(data.Password);
    data.NewPassword = data.NewPassword;
    delete data.NewPassword2;
});

$(function () {
    app.body = $("#Main>#Content") || app.body;

    layoutMain();

    $(window).resize(layoutMain);
});

function layoutMain() {
    var Left = $("#Main>#Left");

    var Page = $("#Main>#Left>#Page");

    var SystemLogo = $("#Main>#Left>#SystemLogo");
    var SystemName = $("#Main>#Left>#SystemName");
    var SystemInfo = $("#Main>#Left>#SystemInfo");

    Page.height(Left.height() - SystemLogo.height() - SystemName.height() - SystemInfo.height() - 30);
}